import 'package:dio/dio.dart';
import 'package:enjoy_pro_max/utils/eventbus.dart';
import 'package:enjoy_pro_max/utils/token.dart';

class NetworkService {
  final _dio = Dio();

  NetworkService() {
    // 配置基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 10);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 10);
    _addInterceptors();
  }

  /// 封装 get 请求
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      Response res = await _dio.get(url, queryParameters: params);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

//post 请求
  Future<dynamic> post(String url, {data}) async {
    try {
      Response res = await _dio.post(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  //put 请求
  Future<dynamic> put(String url, {data}) async {
    try {
      Response res = await _dio.put(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  //delete 请求
  Future<dynamic> delete(String url, {data}) async {
    try {
      Response res = await _dio.delete(url, data: data);
      return _handleResponse(res);
    } catch (error) {
      _handleError(error);
    }
  }

  // 添加拦截器
  _addInterceptors() {
    // 添加拦截器
    _dio.interceptors.add(
      InterceptorsWrapper(
        // 请求拦截器
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          final res = TokenManager().getToken();
          if (res != null) {
            options.headers['Authorization'] = 'Bearer $res';
          }
          // 代办: 添加一些自定义参数 如 token 信息
          return handler.next(options);
        },
        // 响应拦截器
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          // 打印响应数据
          print(response.data);
          return handler.next(response);
        },
        // 错误拦截器
        onError: (DioException error, ErrorInterceptorHandler handler) {
          return handler.next(error);
        },
      ),
    );
  }

  // 请求成功处理
  _handleResponse(Response res) {
    // 判断状态码 >= 200 && <= 300
    if (res.statusCode! >= 200 && res.statusCode! <= 300) {
      return res.data;
    } else {
      throw Exception('请求失败，状态码：${res.statusCode}');
    }
  }

  dynamic _handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if (error.response?.statusCode == 401) {
          TokenManager().removeToken();
          eventBus.fire(LogoutEvent(''));
        } else {
          throw Exception('响应错误，状态码：${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

// 单例模式，导出 NetworkService 的实例
final http = NetworkService();
